interface StorageUtilParams {
  prefixKey?: string; // 前缀
  timeout?: number; // 保留多久
  storage?: Storage; // 用什么缓存
}

interface StorageItem {
  value: any;
  time?: number; // 放入时间戳
  expireTime?: number; // 过期时间戳
}

class StorageUtil {
  private timeout?: number;
  private prefixKey: string;
  private storage: Storage;
  constructor({ prefixKey = "", timeout, storage = window.localStorage }: StorageUtilParams) {
    this.prefixKey = prefixKey;
    this.timeout = timeout;
    this.storage = storage;
  }

  getKey(key: string) {
    return `${this.prefixKey}_${key}`.toUpperCase();
  }
  setItem(key: string, value: any) {
    const currentTimestamp = new Date().getTime();
    const valObj: StorageItem = {
      value,
      time: currentTimestamp,
      expireTime: this.timeout ? currentTimestamp + this.timeout : undefined,
    };
    this.storage.setItem(this.getKey(key), JSON.stringify(valObj));
  }
  getItem(key: string) {
    const val = this.storage.getItem(this.getKey(key));
    if (val) {
      const valObj = JSON.parse(val);
      if (!valObj.expireTime || valObj.expireTime > new Date().getTime()) {
        return valObj.value;
      } else {
        this.removeItem(this.getKey(key));
      }
    }
    return null;
  }

  removeItem(key: string) {
    this.storage.removeItem(this.getKey(key));
  }
}

export default StorageUtil;
